package servlet;

import Dao.JdbcTools;
import model.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/DelUser")
public class StuDel extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1,获取删除的那一条记录的id
        String id = req.getParameter("id");
        System.out.println(id);
        //2.调用Dao层的删除api进行删除操作

        try {
            int del = JdbcTools.del("delete from student where id=?", id);
            if (del > 0) {
                System.out.println(id);
                //删除成功之后，重新获取数据，动态生成前端页面
                try {
                    //获取数据库中展示数据
                    List<Student> stulist = JdbcTools.queryBeanList("select * from student", Student.class);
                    //数据展示 servlet
//                    req.setAttribute("stulist", stulist);
//                    req.getRequestDispatcher("showlist").forward(req, resp);
                    req.setAttribute("stulist", stulist);
                    req.getRequestDispatcher("showlist1.jsp").forward(req, resp);
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }


        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
